package com.bjpowernode.controller;


import com.bjpowernode.common.result.Result;
import com.bjpowernode.entity.query.CustomerQuery;
import com.bjpowernode.service.CustomerService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RequiredArgsConstructor
@RestController
public class CustomerController {

    private final CustomerService customerService;

    @PostMapping("/api/customer")
    public Result convertCustomer (@RequestBody CustomerQuery customerQuery) {
         if(customerService.convertCustomer(customerQuery) > 0) {
             return Result.OK("客户转换成功");
         } else {
             return Result.FAIL("客户转换失败");
         }
    }

    @GetMapping("/api/customer")
    public Result getCustomerByPage(Integer current){
        return  Result.OK(customerService.getCustomerByPage(current));
    }

    //客户信息导出
    @GetMapping("/api/exportExcel")
    public void exportExcel(HttpServletResponse response, @RequestParam("ids") String ids, @RequestParam("pageNum") Integer pageNum) throws IOException {
        List<String> idList = null;
        if (ids != null && !ids.isEmpty()) {
            idList = List.of(ids.split(","));
        }

        //设置响应内容类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        //告诉前端这次返回的是一个文件
        response.setHeader("Content-Disposition", "attachment; filename*=utf-8''" + System.currentTimeMillis() + ".xlsx");

        customerService.exportExcel(response.getOutputStream(), idList, pageNum);
    }

    @GetMapping("/api/customer/{id}")
    public Result getCustomerById(@PathVariable("id") Integer id) {
        return Result.OK(customerService.getCustomerById(id));
    }

}
